package hhm.wcnmd.core.exection;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public abstract class TimeoutExecution<T> {

	private volatile Exception exception;

	private CountDownLatch latch;

	private T result;

	/**
	 * 需要实现的具体执行内容
	 *
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	protected abstract T execute() throws Exception;

	/**
	 * 超时限制执行
	 *
	 * @param timeout
	 *            超时时间数值
	 * @param unit
	 *            超时时间单位
	 * @return true，没有超时正常返回，false 超时
	 */
	public boolean execute(int timeout, TimeUnit unit) {
		result = null; // 清楚上次数据
		latch = new CountDownLatch(1);
		InnerThread innerThread = new InnerThread(); // 初始化内部执行线程
		innerThread.start();

		boolean isNotTimeout = true;
		try {
			isNotTimeout = latch.await(timeout, unit); // 等待执行完毕
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (!isNotTimeout) {
			innerThread.interrupt(); // 终止连接线程
		}

		return isNotTimeout;
	}

	private class InnerThread extends Thread {

		@Override
		public void run() {
			try {
				result = execute(); // 存储执行结果
			} catch (Exception e) {
				exception = e; // 存储执行异常
			} finally {
				latch.countDown(); // 释放等待
			}
		}

	}

	public T getResult() {
		return result;
	}

	public Exception getException() {
		return exception;
	}
}